package com.huli.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.*;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huli.configuration.AlipayConfig;
import com.huli.domain.Owner;
import com.huli.feign.IncomeClient;
import com.huli.feign.OrdersClient;
import com.huli.param.OrdersByOwnerParam;
import com.huli.param.OwnerIncomeParam;
import com.huli.param.OwnerParam;
import com.huli.service.OwnerService;
import com.huli.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;


@Api(tags = "位主接口")
@RestController
@RequestMapping("/owner")
public class OwnerController {

    @Autowired
    private OwnerService ownerService;

    @Autowired
    private IncomeClient incomeClient;

    @Autowired
    private OrdersClient ordersClient;


    /**
     * 位主注册
     */
    @Transactional
    @ApiOperation("位主注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ownerAccount", value = "位主账户", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerEmail", value = "位主邮件", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerPassword", value = "位主密码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerNickname", value = "位主昵称", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerName", value = "位主姓名", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerSex", value = "位主性别", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerPhone", value = "位主电话", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerIdcard", value = "位主身份证", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerVipId", value = "位主Vip", paramType = "query"),
            @ApiImplicitParam(name = "ownerVipTime", value = "位主Vip到期时间", paramType = "query"),
            @ApiImplicitParam(name = "ownerMoney", value = "位主余额", paramType = "query")
    })
    @PostMapping("/register")
    public Result registerOwner(OwnerParam ownerParam) {
        //复制属性
        Owner owner = new Owner();
        BeanUtil.copyProperties(ownerParam, owner);

        //查询账号是否已存在,根据Email判断
        QueryWrapper<Owner> ownerWrapper = new QueryWrapper<>();
        ownerWrapper.eq("owner_email", ownerParam.getOwnerEmail());
        Owner one = ownerService.getOne(ownerWrapper);

        if (one == null)
            return Result.successResult(ownerService.save(owner) ? "注册成功" : "失败");

        return Result.failedResult(400, "已被注册");
    }

    /**
     * 根据ID查询位主信息
     */
    @ApiOperation("根据位主Id查寻位主信息")
    @ApiImplicitParam(name = "ownerId", value = "位主Id", required = true)
    @GetMapping("selectOwnerById")
    public Result selectOwnerById(OwnerParam ownerParam) {
        return Result.successResult(ownerService.selectOwnerById(ownerParam));
    }

    /**
     * 登录
     */
    @ApiOperation("登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ownerAccount", value = "位主账号", required = true),
            @ApiImplicitParam(name = "ownerPassword", value = "位主密码", required = true)
    })
    @GetMapping("login")
    public Result Login(OwnerParam ownerParam) {
        String token = ownerService.login(ownerParam);
        System.out.println("-----------------------------------------------------------------");
        System.out.println(token);
        System.out.println("-----------------------------------------------------------------");
        return Result.successResult(token);
    }

    /**
     * 查询收入
     */
    @ApiOperation("查询收入")
    @GetMapping("queryIncome")
    public Result queryIncome(OwnerParam ownerParam) {
        OwnerIncomeParam ownerIncomeParam = new OwnerIncomeParam();
        BeanUtils.copyProperties(ownerParam, ownerIncomeParam);
        if (ownerParam.getOwnerVipId() == 0) {
            return incomeClient.selectOwnerMonthIncomeById(ownerIncomeParam);
        } else {
            return incomeClient.selectOwnerDayIncomeById(ownerIncomeParam.getOwnerId());
        }
    }

    /**
     * 购买会员
     * 选择购买会员的段位
     * 查询段位的金额,与时长
     * 判断余额是否足够
     * 足够扣除金额,增加时间
     * 不够,返回余额不足失败信息
     * <p>
     * 扣除金额
     * 加时间
     * 生成vipId,更改位主vip字段
     *
     * @param ownerParam
     * @return
     */
    @ApiOperation("购买Vip")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ownerId", value = "位主Id", required = true, paramType = "query"),
            @ApiImplicitParam(name = "ownerVipId", value = "会员档位", required = true, paramType = "query"),
    })
    @PutMapping("buyVip")
    public Result buyVip(OwnerParam ownerParam) {
        return Result.successResult(ownerService.buyVip(ownerParam));
    }


    /**
     * 查询订单
     */
    @GetMapping("selectOrder")
    public Result selectOrder(OwnerParam ownerParam) {
        OrdersByOwnerParam ordersByOwnerParam = new OrdersByOwnerParam();
        ordersByOwnerParam.setOwnerId(ownerParam.getOwnerId());

        return ordersClient.getOwnerOrders(ordersByOwnerParam);
    }

    /**
     * 修改余额
     */
    @PutMapping("updateOwnerMoney")
    public Result updateOwnerMoney(OwnerParam ownerParam) {
        String s = ownerService.updateOwnerMoney(ownerParam);
        return Result.successResult(s);
    }

    /*
        修改位主vip
     */
    @DeleteMapping("/deleteOwnerVip")
    public void deleteOwnerVip() {
        ownerService.deleteOwnerVip();

    }

    /**
     * 支付宝
     */
    @GetMapping ("alipayTest")
    public String alipayTest() {

        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,
                "json",
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);


        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //根据时间生成订单号
        String out_trade_no = new Date().toInstant().toString().substring(0, 9).replace("-", "") + new Date().getTime();

        //付款金额，必填
        String total_amount = "6999";

        String subject="PlayStation 5";
        String body = "充值余额";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String s = null;
        try {
            s = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return s;
    }



    @GetMapping("pay")
    public  AlipayFundTransUniTransferResponse alipayGet(){
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,
                "json",
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);

        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\"201806300001\"," +
                "\"trans_amount\":23.00," +
                "\"scene\":bar_code," +
                "\"auth_code\":," +
                "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +
                "\"biz_scene\":\"DIRECT_TRANSFER\"," +
                "\"order_title\":\"转账标题\"," +
                "\"payee_info\":{" +
                "\"identity\":\"fwrxka0317@sandbox.com\"," +
                "\"identity_type\":\"ALIPAY_LOGON_ID\"," +
                "    }," +
                "\"remark\":\"单笔转账\"," +
                "\"business_params\":\"{\\\"sub_biz_scene\\\":\\\"REDPACKET\\\"}\"" +
                "  }");
        AlipayFundTransUniTransferResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
            return response;
    }

}
